//
//  NMAvatarNode.swift
//  NetEaseMusic
//
//  Created by SAGESSE on 2020/2/28.
//  Copyright © 2020 SAGESSE. All rights reserved.
//

import UIKit
import AsyncDisplayKit


class NMAvatarNode: ASDisplayNode {
  
    var url: URL? {
        set { return avatarNode.url = newValue }
        get { return avatarNode.url }
    }
    
    var auth: Int = 0 {
        willSet {
            switch newValue {
            case 4: // isMusician
                badgeNode.image = #imageLiteral(resourceName: "cm2_icn_musician")
                
            case 300: // isAdmin
                badgeNode.image = #imageLiteral(resourceName: "cm5_icn_admin_48")

            case 1 ... 99: // isRedV
                badgeNode.image = #imageLiteral(resourceName: "cm2_icn_v")
                
            case 200 ... 299: // isExpert
                badgeNode.image = #imageLiteral(resourceName: "cm2_icn_daren")
                
            default:
                badgeNode.image = nil
            }
        }
    }
    
    var pendant: URL? {
        set { return pendantNode.url = newValue }
        get { return pendantNode.url }
    }
    
    override init() {
        super.init()
        
        self.pendantNode.contentMode = .scaleToFill
        self.avatarNode.isLayerBacked = true
        
        self.pendantNode.contentMode = .scaleToFill
        self.pendantNode.isLayerBacked = true
        
        self.badgeNode.style.preferredSize = .init(width: 16, height: 16)
        self.badgeNode.contentMode = .scaleToFill
        self.badgeNode.isLayerBacked = true

        //self.pendantNode.url = URL(string: "http://p1.music.126.net/dLSbU5iZiia1FG37E7z0Vw==/109951164094511660.jpg")
        //self.pendantNode.url = URL(string: "http://p1.music.126.net/_giuOi4B0PRGn5QZG25osQ==/109951164094513651.jpg")
        
        self.addSubnode(self.avatarNode)
        self.addSubnode(self.pendantNode)
        self.addSubnode(self.badgeNode)
    }
    
    override func layoutDidFinish() {
        super.layoutDidFinish()
        self.avatarNode.cornerRadius = self.avatarNode.bounds.size.width / 2
    }
    
    override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
        
        let p1 = ASInsetLayoutSpec(insets: .init(top: 10, left: 10, bottom: 10, right: 10), child: avatarNode)
        let p2 = badgeNode.insets(top: .infinity, left: .infinity, bottom: 9, right: 4)
        
        return ASOverlayLayoutSpec.overlay(pendantNode, p1, p2)
    }
    
//    @IBInspectable
//    open var avatar: UIImage? {
//        set { return contentView.image = newValue }
//        get { return contentView.image }
//    }
//
//    @IBInspectable
//    open var badge: UIImage? {
//        willSet {

    private var badgeNode: ASImageNode = .init()
    private var avatarNode: NMNetworkImageNode = .init()
    private var pendantNode: ASNetworkImageNode = .init()
}
